const Users = require('../../models/users')
const Log = require('../../models/log')
const redis = require('redis')
const jwt = require('jsonwebtoken')
const configs = require('../../config')
const utils_index = require('../../utils/index')
const key = configs.json_web_token_key
const $ = require('../../utils/common')

// todo redis存储时间
// todo 验证码
/**
 * 登出
 * @param {*} request 
 * @param {*} response 
 */
let logout = async function (request, response) {
    // 检查参数
    if ($.isEmpty(request.query.token)) {
        response.end('token 不存在')
        return
    }
    try {
        let token = request.query.token

        // 解析token
        let verify_token_data = await jwt.verify(token, key, (err, data) => {
            if (err) {
                response.end('无效 token')
                return
            }
            return data
        })

        // 解析token后从redis获取 token
        var redis_client = await redis.createClient({port:redis_config.PORT, host: redis_config.HOST,no_ready_check: true})
        redis_client.get(verify_token_data.user_name, (err, data) => {
            if (err) {
                $.sendMessage(response, 1015, '不存在的token')
                return
            }

            if (data == null) {
                $.sendMessage(response, 1015, '不存在的token')
                return
            }

            // 如果不一样
            if (data != token) {
                $.sendMessage(response, 1015, '错误的token, 越权')
                return
            }

            // 如果前端传的token和从redis获取的token一样则删除token
            if (data == token) {
                // 从redis删除token
                redis_client.del(verify_token_data.user_name, (err) => {
                    if (err) {
                        $.sendMessage(response, 1015, 'redis删除错误, 请联系管理员')
                        return
                    }
                    $.sendMessage(response, 1015, '已退出登陆')
                    return
                })
                
            }
            return data
        })

    } catch(err) {
        $.sendMessage(response, 1015, 'error' + err)
        return
    }
}

/**
 * 登陆
 * @param {*} request 
 * @param {*} response 
 */
let login = async function (request, response) {
    try {
        const request_method = request.method
        const request_url = request._parsedUrl.pathname
        const request_ip = utils_index.getClientIp(request)
        // 参数检查
        if (request.body.user_name && request.body.user_password) {
            // 数据了查询用户
            var user_data = {
                user_name: '',
                user_role: '',
                ip: '',
                timestap: '',
                token: ''
            }
            let user =  await Users.findOne(
                {
                    attributes: ['id', 'user_name', 'user_password', 'user_role', 'user_status'],
                    where: {
                    user_name: request.body.user_name,
                    user_password: request.body.user_password
                    }
                }
            )

            if (user === null) {
                response.json({
                    message: '用户账号或密码有误'
                })
                Log.create({
                    user_name: request.body.user_name,
                    user_ip: request_ip,
                    request_url: request_url,
                    request_method: request_method,
                    request_parameter: JSON.stringify(request.body),
                    request_module: '登陆',
                    request_behavior: '登入',
                    request_status: '用户账号或密码有误'
                })
                return
            } else if (user !== null) {
                const user_status = user.dataValues.user_status
                if (user_status != '1') {
                    response.json({
                        code: 1018,
                        message: '账号被停用请联系管理员'
                    })
                    return
                }
                user_data.user_name = user.dataValues.user_name
                user_data.user_role = user.dataValues.user_role
                const user_info = {
                    user_name: user.dataValues.user_name,
                    user_role: user.dataValues.user_role
                }
                var get_token_result = await jwt.sign(user_info, key)
                user_data.token = get_token_result
        

                // token 存到redis
                var redis_client = await redis.createClient(configs.redis_config.PORT, configs.redis_config.HOST)
                var redis_set_result = await redis_client.set(request.body.user_name, user_data.token)// 成功返回false

                if (!redis_set_result) {
                    // 获取用户最近登陆的信息
                    var user_log =  await Log.findOne({
                        order: [
                            ['createdAt', 'DESC'],
                        ],
                        where: {
                            user_name: user_data.user_name
                        },
                        attributes: ['user_ip', 'createdAt']
                    })
                    if (user_log) {
                        user_data.ip = user_log.dataValues.user_ip
                        user_data.timestap = user_log.dataValues.createdAt
                    }
                    response.json({
                        message: 'success',
                        data: user_data
                    })
                    Log.create({
                        user_name: request.body.user_name,
                        user_ip: request_ip,
                        request_url: request_url,
                        request_method: request_method,
                        request_parameter: JSON.stringify(request.body),
                        request_module: '登陆',
                        request_behavior: '登入',
                        request_status: '成功'
                    })
                    
                } else if (redis_set_result) {
                    $.sendMessage(response, 1015, 'redis error')
                    return
                }
            }
        } else {
            response.json({
                message: '参数错误'
            })
            return
        }
    } catch(err) {
        $.sendMessage(response, 1015, 'error：' + err)
        return
    }
}

module.exports.login = login
module.exports.logout = logout